/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.forum.pages;

import com.alee.extended.label.WebLinkLabel;
import com.alee.extended.layout.VerticalFlowLayout;
import com.alee.extended.panel.GroupPanel;
import com.alee.laf.label.WebLabel;
import com.alee.laf.panel.WebPanel;
import com.alee.laf.scroll.WebScrollPane;
import com.alee.laf.separator.WebSeparator;
import com.alee.laf.text.WebEditorPane;
import com.alee.utils.WebUtils;
import com.rag.core.NewsData;
import com.rag.core.SingleNews;
import com.rag.managers.UpdateManager;
import com.rag.managers.update.NewsListener;
import info.clearthought.layout.TableLayout;

import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.text.SimpleDateFormat;

/**
 * User: mgarin Date: 12.04.12 Time: 17:18
 */

public class NewsPage extends WebPanel
{
    public static final SimpleDateFormat sdf = new SimpleDateFormat ( "dd.MM HH:mm" );

    public NewsPage ()
    {
        super ();

        // Слушатель входящих новостей
        UpdateManager.addNewsListener ( new NewsListener ()
        {
            public void announceUpdated ( SingleNews announceNews )
            {
                updateNewsPage ();
            }

            public void newsUpdated ( SingleNews updatedNews )
            {
                updateNewsPage ();
            }
        } );

        // Первоначальная загрузка
        new Thread ( new Runnable ()
        {
            public void run ()
            {
                if ( !UpdateManager.loadNews () )
                {
                    updateNewsPage ();
                }
            }
        } ).start ();
    }

    private void updateNewsPage ()
    {
        WebPanel list = new WebPanel ( new VerticalFlowLayout () );
        list.setMargin ( 5 );

        // Анонсы
        NewsData announceData = UpdateManager.getAnnounceData ();
        if ( announceData != null )
        {
            if ( announceData.getNews ().size () > 0 )
            {
                list.add ( createSeparatorPanel ( "Анонсы" ) );
            }

            for ( SingleNews news : announceData.getNews () )
            {
                list.add ( createSingleNewsPanel ( news ) );
            }
        }

        // Новости
        NewsData newsData = UpdateManager.getNewsData ();
        if ( newsData != null )
        {
            if ( newsData.getNews ().size () > 0 )
            {
                list.add ( createSeparatorPanel ( "Новости" ) );
            }

            for ( SingleNews news : newsData.getNews () )
            {
                list.add ( createSingleNewsPanel ( news ) );
            }
        }

        NewsPage.this.removeAll ();

        WebScrollPane scrollPane = new WebScrollPane ( list, false )
        {
            public Dimension getPreferredSize ()
            {
                Dimension ps = super.getPreferredSize ();
                ps.height = 1;
                return ps;
            }
        };
        scrollPane.setOpaque ( false );
        NewsPage.this.add ( scrollPane );


        NewsPage.this.revalidate ();
        NewsPage.this.repaint ();
    }

    private WebPanel createSeparatorPanel ( String title )
    {
        WebPanel separatorPanel = new WebPanel ();
        separatorPanel.setLayout ( new TableLayout (
                new double[][]{ { TableLayout.FILL, TableLayout.PREFERRED, TableLayout.FILL },
                        { TableLayout.FILL, TableLayout.PREFERRED, TableLayout.FILL } } ) );

        WebLabel label = new WebLabel ( title, WebLabel.CENTER );
        label.setMargin ( 0, 4, 3, 4 );
        label.setOpaque ( true );
        separatorPanel.add ( label, "1,0,1,2" );

        separatorPanel.add ( new WebSeparator ( WebSeparator.HORIZONTAL ), "0,1,2,1" );

        return separatorPanel;
    }

    private WebPanel createSingleNewsPanel ( SingleNews news )
    {
        String date = sdf.format ( news.getDate () );

        final WebLabel newsTitle = new WebLabel ( "<html><b>" + news.getTitle () + "</b><br>" +
                "<font size='2'>[ Дата публикации: " + date + " ]</font></html>" );
        newsTitle.setMargin ( 0, 0, 4, 0 );

        WebLabel iconLabel = new WebLabel ( news.getType ().getIcon () );
        iconLabel.setVerticalAlignment ( WebLabel.TOP );

        final WebEditorPane newsText = new WebEditorPane ( "text/html",
                news.getText () != null ? "<html>" + news.getText () + "</html>" : null );
        newsText.setOpaque ( false );
        newsText.setEditable ( false );
        newsText.addHyperlinkListener ( new HyperlinkListener ()
        {
            public void hyperlinkUpdate ( HyperlinkEvent e )
            {
                if ( e.getEventType () == HyperlinkEvent.EventType.ACTIVATED &&
                        e.getURL () != null )
                {
                    String address = e.getURL ().toExternalForm ();
                    if ( address.startsWith ( "mailto:" ) )
                    {
                        WebUtils.writeEmailSafely ( address );
                    }
                    else
                    {
                        WebUtils.browseSiteSafely ( address );
                    }
                }
            }
        } );

        Font font = newsTitle.getFont ();
        newsText.setFont ( font.deriveFont ( font.getSize () - 1f ) );

        final WebLinkLabel newsLink = new WebLinkLabel ();
        newsLink.setLink ( news.getLink (), false );
        newsLink.setText ( news.getLink () );

        GroupPanel contentGroup =
                new GroupPanel ( 10, false, newsTitle, newsText, new GroupPanel ( newsLink ) );
        GroupPanel mainGroup =
                new GroupPanel ( 10, iconLabel, new WebSeparator ( WebSeparator.VERTICAL ),
                        contentGroup );
        WebPanel border = new WebPanel ( true, mainGroup );
        border.setShadeWidth ( 5 );
        border.setMargin ( 10 );
        border.setWebColored ( false );
        border.setBackground ( new Color ( 248, 248, 248 ) );
        return border;
    }
}